package org.csu.mypetstore.controller;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.domain.Sms;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.SmsService;
import org.csu.mypetstore.service.VerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping("account")
@SessionAttributes({"account", "myList" ,"authenticated"})
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private SmsService smsService;

    private Sms sms;

    private String imageMess;
    private int codeIsTrue;
    private int codeIsRight;
    private static final List<String> LANGUAGE_LIST;
    private static final List<String> CATEGORY_LIST;

    static {
        List<String> langList = new ArrayList<String>();
        langList.add("english");
        langList.add("japanese");
        LANGUAGE_LIST = Collections.unmodifiableList(langList);

        List<String> catList = new ArrayList<String>();
        catList.add("FISH");
        catList.add("DOGS");
        catList.add("REPTILES");
        catList.add("CATS");
        catList.add("BIRDS");
        CATEGORY_LIST = Collections.unmodifiableList(catList);
    }

    @GetMapping("signonForm")
    public String signonForm(){
        return "account/signon";
    }
    @GetMapping("phonelogin")
    public String phoneSignon(){
        return "account/phone_login";
    }
    @PostMapping("signonForm")
    public String signonform(Model model){
        VerifyService vc = new VerifyService();
        //获取图片对象
        BufferedImage bi = vc.getImage();
        //获得图片的文本内容
        String imageMess = vc.getText();
        model.addAttribute("imageMess",imageMess);
        return "account/signon";
    }
    @PostMapping("newAccountForm")
    public String newaccountForm(Model model){
        VerifyService vc = new VerifyService();
        //获取图片对象
        BufferedImage bi = vc.getImage();
        //获得图片的文本内容
        String imageMess = vc.getText();
        model.addAttribute("imageMess",imageMess);
        return "account/new_account";
    }


    @PostMapping("signon")
    public String signon (String username, String password, Model model, HttpSession session){

        //加密
        MessageDigest md5 = null;
        try{
            md5 = MessageDigest.getInstance("MD5");
        }catch (Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = password.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++){
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }

        String newPassword = hexValue.toString();

        Account account = accountService.getAccount(username,newPassword);

        if (account == null||codeIsTrue!=1) {
            String msg = "Invalid .  Signon failed.";
            model.addAttribute("msg", msg);
            return "account/signon";
        } else {
            account.setPassword(null);
            List<Product> myList = catalogService.getProductListByCategory(account.getFavouriteCategoryId());
            boolean authenticated = true;
            model.addAttribute("account",account);
            model.addAttribute("myList",myList);
            model.addAttribute("authenticated",authenticated);
            return"catalog/main";
        }
    }
    @PostMapping("signonbyphone")
    public String signonbyphone (String Number, Model model, HttpSession session){
        Account account = accountService.getAccountbyPhonenumber(Number);
        if (Number.length() != 11){
            String msg = "手机号格式出错";
            model.addAttribute("msg", msg);
            return "account/phone_login";
        }
        else if (account == null|| codeIsRight!=1) {
            String msg = "Invalid .  Signon failed.";
            model.addAttribute("msg", msg);
            return "account/phone_login";
        } else if(codeIsRight==1){
            account.setPassword(null);
            List<Product> myList = catalogService.getProductListByCategory(account.getFavouriteCategoryId());
            boolean authenticated = true;
            model.addAttribute("account",account);
            model.addAttribute("myList",myList);
            model.addAttribute("authenticated",authenticated);
            return"catalog/main";
        }
        else return "account/phone_login";
    }

    @GetMapping("/signoff")
    public String signoff(Model model){
        Account loginAccount = new Account();
        List<Product> myList = null;
        boolean authenticated = false;
        model.addAttribute("account",loginAccount);
        model.addAttribute("authenticated",authenticated);
        model.addAttribute("myList",myList);
        return "catalog/main";
    }

    @GetMapping("editAccountForm")
    public String editAccountForm(@SessionAttribute("account") Account account, Model model){
        model.addAttribute("account",account);
        model.addAttribute("LANGUAGE_LIST",LANGUAGE_LIST);
        model.addAttribute("CATEGORY_LIST",CATEGORY_LIST);
        return"account/edit_account";
    }

    @PostMapping("editAccount")
    public String editAccount (Account account, String repeatedPassword, Model model){
        if (account.getPassword() == null|| account.getPassword().length() == 0|| repeatedPassword == null || repeatedPassword.length() == 0){
            String msg = "密码不能为空";
            model.addAttribute("msg",msg);
            return "account/edit_account";
        }else if (!account.getPassword().equals(repeatedPassword)){
            String msg = "两次密码不一致";
            model.addAttribute("msg",msg);
            return "account/edit_account";
        }
        else {
            accountService.updateAccount(account);
            account = accountService.getAccount(account.getUsername());
            List<Product> myList = catalogService.getProductListByCategory(account.getFavouriteCategoryId());
            boolean authenticated = true;
            model.addAttribute("account",account);
            model.addAttribute("myList",myList);
            model.addAttribute("authenticated",authenticated);
            return "redirect:/catalog/view";
        }
    }

    @GetMapping("newAccountForm")
    public String newAccountForm(Model model){
        model.addAttribute("newAccount" ,new Account());
        model.addAttribute("LANGUAGE_LIST",LANGUAGE_LIST);
        model.addAttribute("CATEGORY_LIST",CATEGORY_LIST);
        return "account/new_account";
    }


    @PostMapping("newAccount")
    public String newAccount(String username,String password,String repeatedPassword,String phonenumber,Account account, Model model){

        if (accountService.getAccount(username) != null){
            String msg = "用户名已经注册";
            model.addAttribute("msg", msg);
            model.addAttribute("newAccount" ,new Account());
            model.addAttribute("LANGUAGE_LIST",LANGUAGE_LIST);
            model.addAttribute("CATEGORY_LIST",CATEGORY_LIST);
            boolean authenticated = false;
            model.addAttribute("authenticated", authenticated);
            return "/account/new_account";
        }else if (account.getUsername()==null || account.getPassword() == null || account.getPassword().length() == 0
                || repeatedPassword == null || repeatedPassword.length() == 0) {
            String msg = "用户名或密码不能为空";
            model.addAttribute("msg", msg);
            model.addAttribute("newAccount" ,new Account());
            model.addAttribute("LANGUAGE_LIST",LANGUAGE_LIST);
            model.addAttribute("CATEGORY_LIST",CATEGORY_LIST);
            boolean authenticated = false;
            model.addAttribute("authenticated", authenticated);
            return "/account/new_account";
        } else if (!account.getPassword().equals(repeatedPassword)) {
            System.out.println("两次密码不一致");
            String msg = "两次密码不一致";
            model.addAttribute("msg", msg);
            model.addAttribute("newAccount" ,new Account());
            model.addAttribute("LANGUAGE_LIST",LANGUAGE_LIST);
            model.addAttribute("CATEGORY_LIST",CATEGORY_LIST);
            boolean authenticated = false;
            model.addAttribute("authenticated", authenticated);
            return "/account/new_account";
        } else if (codeIsTrue!=1) {
            System.out.println("验证码输入有误!");
            String msg = "验证码输入有误!";
            model.addAttribute("msg", msg);
            model.addAttribute("newAccount" ,new Account());
            model.addAttribute("LANGUAGE_LIST",LANGUAGE_LIST);
            model.addAttribute("CATEGORY_LIST",CATEGORY_LIST);
            boolean authenticated = false;
            model.addAttribute("authenticated", authenticated);
            return "/account/new_account";
        }

        if (phonenumber.length()!=0){
            if(accountService.getAccountbyPhonenumber(phonenumber) != null) {
                String msg = "该手机已经注册";
                model.addAttribute("msg", msg);
                model.addAttribute("newAccount", new Account());
                model.addAttribute("LANGUAGE_LIST", LANGUAGE_LIST);
                model.addAttribute("CATEGORY_LIST", CATEGORY_LIST);
                boolean authenticated = false;
                model.addAttribute("authenticated", authenticated);
                return "/account/new_account";
            }
        }

            //加密
            MessageDigest md5 = null;
            try{
                md5 = MessageDigest.getInstance("MD5");
            }catch (Exception e){
                System.out.println(e.toString());
                e.printStackTrace();
                return "";
            }
            char[] charArray = password.toCharArray();
            byte[] byteArray = new byte[charArray.length];

            for (int i = 0; i < charArray.length; i++)
                byteArray[i] = (byte) charArray[i];
            byte[] md5Bytes = md5.digest(byteArray);
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++){
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }

            String newPassword = hexValue.toString();
            System.out.println(newPassword);
            account.setPassword(newPassword);

            accountService.insertAccount(account);
            account = accountService.getAccount(account.getUsername());
            List<Product> myList = catalogService.getProductListByCategory(account.getFavouriteCategoryId());
            model.addAttribute("newAccount", account);
            model.addAttribute("myList", myList);
            boolean authenticated = true;
            model.addAttribute("authenticated", authenticated);
            return "redirect:/catalog/view";
        }



    @RequestMapping("checkUser")
    @ResponseBody
    public void checkUser (HttpServletResponse response,@RequestParam String username) throws IOException {
        //System.out.println(username);
        boolean result = accountService.usernameIsnotExist(username);
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        if(!result)
        {
            //System.out.println("Exist username");
            out.print("Exist");
        }else{
            //System.out.println("Not Exist username");
            out.print("Not Exist");
        }
    }
    @RequestMapping("pictureCheckCode")
    @ResponseBody
    public void pictureCheckCode (HttpServletResponse response) throws IOException {
        VerifyService vc = new VerifyService();
        //获取图片对象
        BufferedImage bi = vc.getImage();
        //获得图片的文本内容
        accountService.insertLog("VerifyCode","Display/Flush VerifyCode!", "null");
        imageMess = vc.getText();

        System.out.println("    0000000000000000"+imageMess);
        //向浏览器输出图片
        vc.output(bi, response.getOutputStream());
    }
    @GetMapping("checkCode")
    @ResponseBody
    public void checkCode (Model model,HttpServletResponse response,@RequestParam String code) throws IOException {
        PrintWriter out = response.getWriter();
        System.out.println(imageMess+"    "+code);
        if (code.equals(imageMess))
        {
            codeIsTrue=1;
            out.print("T");
        }
        else{
            codeIsTrue=0;
            out.print("F");
        }
        out.flush();
        out.close();
    }

    //后台获得验证码
    @RequestMapping("send")
    @ResponseBody
    public void checkCode(@RequestParam String number) throws ClientException, IOException {

        sms.setNewcode();
        String code = Integer.toString(Sms.getNewcode());
        System.out.println("发送的验证码为："+code);
        //发短信

        SendSmsResponse res = smsService.sendSms(number,code);
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + res.getCode());
        System.out.println("Message=" + res.getMessage());
        System.out.println("RequestId=" + res.getRequestId());
        System.out.println("BizId=" + res.getBizId());
    }
    @RequestMapping("compare")
    @ResponseBody
    public void compareCode(HttpServletResponse response,@RequestParam String code) throws IOException {

        PrintWriter out = response.getWriter();
        int c = sms.getNewcode();
        System.out.println(code+"     "+c);
        if(c==Integer.parseInt(code))
        {
            System.out.println("T");
            codeIsRight=1;
            out.print("T");
        }
        else {
            out.print("F");
        }
    }


}
